<template>
  <div class="search-container">
    <!-- 搜索页面头部 -->
    <div class="search-header">
      <!-- 后退按钮 -->
      <van-icon
        name="arrow-left"
        color="white"
        size="0.48rem"
        class="goback"
        @click="$router.back()"
      />
      <!-- 搜索组件 -->
      <van-search
        v-model="keyword"
        placeholder="请输入搜索关键词"
        background="#007BFF"
        shape="round"
        v-focus
        @input="inputFn"
        @search="goto(keyword)"
      />
    </div>
    <ul class="sugg-list" v-if="searchList.length">
      <li
        class="sugg-item"
        v-for="(item, i) in searchList"
        :key="i"
        v-html="handleSugg(item)"
        @click="goto(item)"
      ></li>
    </ul>
    <!-- 搜索历史 -->
    <div class="search-history" v-else>
      <!-- 标题 -->
      <van-cell title="搜索历史">
        <!-- 使用 right-icon 插槽来自定义右侧图标 -->
        <template #right-icon>
          <van-icon name="delete" class="search-icon" @click="delFn" />
        </template>
      </van-cell>

      <!-- 历史列表 -->
      <div class="history-list">
        <span
          class="history-item"
          @click="goto(item)"
          v-for="(item, i) in historyList"
          :key="i"
          >{{ item }}</span
        >
      </div>
    </div>
  </div>
</template>

<script>
import { getSuggestListApi } from "@/api/search";
export default {
  name: "SearchViews",
  data() {
    return {
      keyword: "", // 搜索关键字
      searchList: [],
      historyList: JSON.parse(localStorage.getItem("history")) || [],
    };
  },
  watch: {
    // 监听数组是否有变化
    historyList: {
      deep: true,
      handler(newVal) {
        localStorage.setItem("history", JSON.stringify(newVal));
      },
    },
  },
  methods: {
    inputFn() {
      if (this.timer) clearTimeout(this.timer);
      this.timer = setTimeout(async () => {
        if (!this.keyword) return (this.searchList = []);
        const resp = await getSuggestListApi(this.keyword);
        // 关键字高亮
        this.searchList = resp.data.options.filter((str) => str);
      }, 500);
    },
    handleSugg(str) {
      const regexp = new RegExp(this.keyword, "ig");
      // match: 表示str中符合正则规则的字符串
      // 回调函数中return的结果会替换原来字符串中符合正则规则的字符串(目的就是保留原有的大小写)
      return str.replace(
        regexp,
        (match) => `<span style="color: red">${match}</span>`
      );
    },
    // 跳转搜索页面
    goto(str) {
      // 如果没有关键词，提前结束
      if (!str) return;
      if (!this.historyList.includes(str)) {
        this.historyList.push(str);
        this.keyword = "";
      }
      setTimeout(() => {
        this.$router.push(`/Search/${str}`);
      }, 0);
    },
    // 删除历史记录
    async delFn() {
      try {
        await this.$dialog.confirm({
          title: "温馨提示",
          message: "确认清空历史记录吗",
        });
        this.historyList = [];
        this.$toast.success("已清空");
      } catch (error) {
        this.$toast.fail("取消成功");
      }
    },
  },
};
</script>

<style scoped lang="less">
.search-header {
  display: flex;
  align-items: center;
  height: 46px;
  background-color: #007bff;
  overflow: hidden;
  /*后退按钮*/
  .goback {
    padding-left: 14px;
  }
  /*搜索组件*/
  .van-search {
    flex: 1;
  }
}
/*搜索建议列表样式 */
.sugg-list {
  .sugg-item {
    padding: 0 15px;
    border-bottom: 1px solid #f8f8f8;
    font-size: 14px;
    line-height: 50px;
    // 实现省略号的三行代码
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
/**搜索历史 */
.search-icon {
  font-size: 16px;
  line-height: inherit;
}

.history-list {
  padding: 0 10px;
  .history-item {
    display: inline-block;
    font-size: 12px;
    padding: 8px 14px;
    background-color: #efefef;
    margin: 10px 8px 0px 8px;
    border-radius: 10px;
  }
}
</style>